<template>
  <div class="background">
  <div id="car-form" class="form-container" >
    <el-form :model="loginDto" label-width="auto" style="width: 100%;" size="large"
             :rules="rules" ref="refLoginForm">
      <h1 class="form-header">充电桩后台管理系统</h1>
      <el-form-item prop="account">
        <el-input
            v-model="loginDto.account"
            placeholder="请输入账号"
            :prefix-icon="User"
            style="width: 100%; font-size: 20px"
        />
        <template #prepend><span style="width: 50px">用户名</span></template>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
            v-model="loginDto.password"
            type="password"
            placeholder="请输入密码"
            show-password
            :prefix-icon="Lock"
            style="width: 100%; font-size: 20px"
        />
        <template #prepend><span style="width: 50px">密码</span></template>
      </el-form-item>
      <el-form-item label="验证码：" prop="code">
        <div class="form-item-container">
          <el-input v-model="loginDto.code"
                    maxlength="4"
                    minlength="4"
                    placeholder="验证码"
                    style="width: 150px;">
          </el-input>
          <img :src="codeUrl"
               style="cursor: pointer; margin-left: 10px;"
               @click="getCaptcha()"
               title="看不清点击刷新"/>
        </div>

      </el-form-item>
      <el-form-item>
        <el-button :disabled="isButtonDisabled"
                   type="primary" @click="login" style="width: 100%; font-size: 20px">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import {userStore} from '../store/index.js'
import {useRouter} from 'vue-router';



const userItemStore = userStore();
const router = useRouter();

const loginDto = reactive({
  account: 'root',
  password: 'root',
  code: '',
  key: '',

});

//获取验证码
const getCaptcha = () => {
  axios.get('/user/code').then(resp => {
    //返回两个数据：key是Redis中key，base64Img是图片
    codeUrl.value = resp.data.base64Img;
    loginDto.key = resp.data.key;
  })
}
const codeUrl = ref('');


const rules = reactive({
  account: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {min: 4, max: 4, message: '长度必须是4位', trigger: 'blur'}
  ]
});



const refLoginForm = ref(null); // 创建一个 ref 来引用 el-form
const isButtonDisabled = ref(false);
const login = () => {
  // 验证表单
  // const formRef = loginForm.value;
  // 发起登录请求
  refLoginForm.value.validate(valid => {
    if (valid) {
      axios.post('http://e2d8sy.natappfree.cc/user/login', loginDto).then(resp => {
        const user = resp.data;
        localStorage.setItem('token', user.token);
        // 保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));

        //修改保存的用户信息
        userItemStore.updateUser(user)
        //修改状态
        userItemStore.updateLoginStatus(true)
        // 提示登录成功
        ElMessage({
          message: `登录成功，欢迎您：${user.account}！`,
          type: 'success'
        });
        // 跳转到首页
        router.push('/');
      }).catch(error => {
        // 登录失败
        const messageText = error.response.data;
        ElMessage.error(`登录失败，${messageText}`);
      });
    } else {
      return false;
    }
    //让登录按钮变得不可用
    isButtonDisabled.value = true
    // 5秒后变得可用
    setTimeout(() => {
      isButtonDisabled.value = false;
    }, 5000);
  });
}



onMounted(() => {
  //获取验证码
  getCaptcha()
})

</script>

<style scoped>
#car-form {
  width: 400px;
  height: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 10px;
  box-shadow: 8px 10px 10px rgb(177, 223, 242);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: white;
}

.background {
  width: 100vw;
  height: 100vh;
  background-image: url('../assets/back.jpeg'); /* 使用相对路径 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}


.form-header {
  position: relative;
  top: -5px;
  margin-bottom: 20px;
  text-align: center;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.form-item-container {
  display: flex;
  align-items: flex-end;
}
</style>